/*
 * TempSensorDetector.java
 *
 * By Gary Wong, 2005.
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of Version 2 of the GNU General Public 
 * License.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
 * 02110-1301, USA.
 */

package sxe.sensors;

import java.util.Hashtable;
import org.w3c.dom.*;
import snbenchlib.XML;

public class TempSensorDetector {

    private static final String CONFIG_XML_TAG = "temperature";

	public TempSensorDetector() {
	super();
    }

    static public Hashtable<String, GenericSensor> detect(Element eSensorConfigRoot) {
		Hashtable<String, GenericSensor> hashTable = new 
		    Hashtable<String, GenericSensor>();
	
		try {
		    if (eSensorConfigRoot==null)
		    	return hashTable;
		    Node nConfig = XML.getChildNodeMatchingTag(eSensorConfigRoot,CONFIG_XML_TAG);
		    if(nConfig == null)
		    	return hashTable;
	
		    Node n = XML.getChildNodeMatchingTag((Element)nConfig, "basestation");
		    if(n==null)
		    	return hashTable;
		    
			Element e = (Element) n;
	
			String host = e.getAttribute( "host" );
			if( host == null )
				return hashTable;
	
			String port = e.getAttribute( "port" );
				    
			BaseStation baseStation = new BaseStation( 
			    host, port != null ? new Integer( port ) : 9001 );
									   
			Node child;
				
			for( child = e.getFirstChild(); child != null;
			     child = child.getNextSibling() ) {
			    if( child.getNodeType() != Node.ELEMENT_NODE )
				continue;
	
			    Element sensor = (Element) child;
			    if( sensor.getTagName() != "sensor" )
				continue;
	
			    int id = new Integer( sensor.getAttribute( "id" ) );
			    String location = "";
	
			    Node search;
	
			    for( search = sensor.getFirstChild(); search != null;
				 search = search.getNextSibling() )
				if( search.getNodeType() == Node.ELEMENT_NODE &&
				    search.getNodeName() == "location" ) {
				    location = search.getTextContent();
				    break;
				}
			    
			    TempSensor ts = new TempSensor( baseStation, id, 
							    location );
			    hashTable.put( ts.getID(), ts );
			    ts.initializeSensor();
			}
		    
		} catch( Exception ex ) {
		    System.err.println( ex.getMessage() );
		    return hashTable;
		}
	
		return hashTable;
	    }
	}
